//
//  LeftTextRightImageButton.m
//  GTQCitySelector
//
//  Created by 光头强 on 16/7/22.
//  Copyright © 2016年 Ls. All rights reserved.
//

#import "LeftTextRightImageButton.h"
#import "UIView+GTQFrame.h"

@implementation LeftTextRightImageButton
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.titleLabel.contentMode = UIViewContentModeLeft;
        self.titleLabel.font = [UIFont systemFontOfSize:14];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        
        self.imageView.contentMode = UIViewContentModeLeft;
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    NSLog(@"%s",__FUNCTION__);
    self.titleLabel.frame = CGRectMake(0, 0, self.width - 12, self.height);
    self.imageView.frame = CGRectMake(self.width - 10, (self.height - 6) * 0.5, 10, 6);
}

#pragma mark - 重写父类的这个方法
- (void)setTitle:(NSString *)title forState:(UIControlState)state
{
    NSLog(@"%s",__FUNCTION__);
    [super setTitle:title forState:state];
    
    CGRect rect = [self dynamicHeight:title fontSize:14];
    
    CGFloat width = rect.size.width;
    self.frame = CGRectMake(0, 0, width+14, self.height);
}

//计算字符串的大小
- (CGRect)dynamicHeight:(NSString *)str fontSize:(NSInteger)fontSize
{
    UIFont *font = [UIFont systemFontOfSize:fontSize];
    NSDictionary *dict = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    CGRect rect = [str boundingRectWithSize:CGSizeMake(1000, 20) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dict context:nil];
    return rect;
}
@end
